package com.easypay.reactive8583.iso;

import com.solab.iso8583.IsoMessage;
import com.solab.iso8583.parse.ConfigParser;
import com.solab.iso8583.MessageFactory;
import lombok.NonNull;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.text.ParseException;

/**
 * @author pandans
 * @date 2021/03/04 16:02
 * @Description:
 */
public class J8583MessageFactory<T extends IsoMessage> implements com.easypay.reactive8583.iso.MessageFactory<T>{
    private MessageFactory<T> messageFactory;
    private ISO8583Version isoVersion;

    public J8583MessageFactory(ISO8583Version isoVersion) {
        this(null, isoVersion);
    }

    public J8583MessageFactory(MessageFactory<T> messageFactory, ISO8583Version isoVersion) {
        this.messageFactory = messageFactory;
        if(this.messageFactory == null) {
            this.messageFactory = defaultMessageFactory();
        }
        this.isoVersion = isoVersion;
    }

    @Override
    public T newMessage(int type) {
        return messageFactory.newMessage(type);
    }

    @Override
    public T newMessage(@NonNull MessageClass messageClass,@NonNull MessageFunction messageFunction,@NonNull MessageOrigin messageOrigin) {
        return newMessage(new MTI(isoVersion, messageClass, messageFunction, messageOrigin).mtiValue());
    }

    @Override
    public T createResponse(T requestMessage) {
        return messageFactory.createResponse(requestMessage);
    }

    @Override
    public T createResponse(T request, Boolean copyAllFields) {
        return messageFactory.createResponse(request, copyAllFields);
    }

    @Override
    public T parseMessage(byte[] buf, int isoHeaderLength, Boolean binaryIsoHeader) throws ParseException, UnsupportedEncodingException {
        return messageFactory.parseMessage(buf, isoHeaderLength, binaryIsoHeader);
    }

    @Override
    public T parseMessage(byte[] buf, int isoHeaderLength) throws ParseException, UnsupportedEncodingException {
        return messageFactory.parseMessage(buf, isoHeaderLength);
    }

    private MessageFactory<T> defaultMessageFactory() {
        try {
            return (MessageFactory<T>) ConfigParser.createDefault();
        }catch (IOException e){
            return null;
        }
    }
}
